package robotninja.asctec.test.serial;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

/**
 * GUI for testing the Asctec Driver
 * 
 * @author dav & hector
 * 
 */
public class MainActivity extends Activity {

	private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
	private static final String TAG = MainActivity.class.getCanonicalName();
	private boolean connected = false;
	private boolean isPullingData = false;
	private UsbDevice ftdiDevice;
	private TextView outputTV;
	private UsbManager manager;
	private UsbSerialDriver serialDriver;

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					UsbDevice device = (UsbDevice) intent
							.getParcelableExtra(UsbManager.EXTRA_DEVICE);

					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						if (device != null) {
							serialDriver = UsbSerialProber.acquire(manager,
									device);
							try {
								serialDriver.open();
								serialDriver.setParameters(9600, 8, 1, 0);
							} catch (IOException e) {
								e.printStackTrace();
							} finally {
								connected = true;
							}
						}
					} else {
						Log.d(TAG, "permission denied for device " + device);
					}
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		outputTV = (TextView) findViewById(R.id.textView1);
		final Activity act = this;

		manager = (UsbManager) MainActivity.this
				.getSystemService(Context.USB_SERVICE);

		PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0,
				new Intent(ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		registerReceiver(mUsbReceiver, filter);

		
		HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
		Collection<UsbDevice> usbs = deviceList.values();
		for (UsbDevice usbDevice : usbs) {
			if(usbDevice.getProductId() == 24577){
				manager.requestPermission(usbDevice, mPermissionIntent);
			}
		}

		// Connect checkbox.
		CheckBox cbConnect = (CheckBox) findViewById(R.id.checkBoxConnect);
		cbConnect.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				try {

					HashMap<String, UsbDevice> deviceList = manager
							.getDeviceList();
					Log.d("SERIAL", "s:>" + deviceList.keySet().toString());

					Log.d("SERIAL", "s:>" + deviceList.size());
					Collection<UsbDevice> usbs = deviceList.values();
					for (UsbDevice usbDevice : usbs) {
						Log.d("SERIAL",
								"seriales:>" + usbDevice.getDeviceId() + " "
										+ usbDevice.getDeviceName() + " "
										+ usbDevice.getProductId() + " "
										+ usbDevice.describeContents());
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(!isPullingData && connected){
					(new PullSerialDataTask()).execute();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private HashMap<String, Object> getSerialParameters(Activity act) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("Activity", act);
		params.put("baudrate", 57600);
		params.put("dataBits", 8);
		params.put("stopBits", 1);
		params.put("parity", 0);

		return params;
	}

	public class PullSerialDataTask extends AsyncTask<Void, Void, Boolean> {

		public PullSerialDataTask() {
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			isPullingData = true;
			while (isPullingData) {
				byte[] buffer = new byte[100];

				int read = 0;
				try {
					read = serialDriver.read(buffer, 1000);
				} catch (IOException e) {
					Log.d("DATA", e.getMessage());
				}

				if(read > 0){
					String s = "";
					for (int i = 0; i < read; i++) {
						s += Character.toString((char) buffer[i]);
					}
	
					Log.d("DATA", read + ">" + s);
				}

			}
			return isPullingData;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
		}

		@Override
		protected void onCancelled() {

		}
	}
	
}
